import Vue from "vue";
import Vuex from "vuex";
import Api from './api';
import {Toast} from 'vant'

Vue.use(Vuex);

export default new Vuex.Store({
  state: {
    historyList: [],
    shopCartList: [],
  },
  // 以下只能是同步方法
  mutations: {
    addHistory(state, keyword) {
      if (state.historyList.indexOf(keyword) == -1) {
        state.historyList.push(keyword)
      }
    },
    addShopCard(state, goods) {
      state.shopCartList.push(goods);
    }
  },
  // 一下可以是异步方法
  actions: {
    async addShopCard(context, goodsId) {
      let hasStock = await Api.goods.stock(goodsId);
      if (hasStock) {
        let goods = await Api.goods.info(goodsId);
        context.commit('addShopCard', goods)
      } 
      else {
        Toast.fail(`没有库存`)
      }
    }
  }
});